package com.yc.thread.lock;

import java.util.Random;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

public class TestPhaser {
	MyPhaser phaser = new MyPhaser();
	
	public void m() {
		phaser.bulkRegister(5);
		for (int i = 0; i < 5; i++) {
			final int heroId = i;
			new Thread(() -> {
				Hero h = new Hero(heroId+"");
				System.out.println(heroId+"号勇士出发了");
				
				h.pass1();
				phaser.arriveAndAwaitAdvance();
				
				h.pass2();
				phaser.arriveAndAwaitAdvance();
				
				h.pass3();
				phaser.arriveAndAwaitAdvance();
				
				h.pass4();
				phaser.arriveAndAwaitAdvance();
				
			}).start();
			
		}
	}
	
	public static void main(String[] args) {
		TestPhaser tp = new TestPhaser();
		tp.m();

	}
	
	void milliSleep(int milli) {
        try {
            TimeUnit.MILLISECONDS.sleep(milli);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
	
	class MyPhaser extends Phaser {

		@Override
		protected boolean onAdvance(int phase, int registeredParties) {
			
			switch(phase) {
			case 0:
				System.out.println("第1关");
				return false;
			case 1:
				System.out.println("第2关");
				return false;
			case 2:
				System.out.println("第3关");
				return false;
			default:
				System.out.println("大家通关成功！");
				return true;
			
			}
			
		}
		
	}
	
	//勇士
	class Hero {
		String name;
		public Hero(String name) {
			this.name = name;
		}
		
		
		
		public void pass1() {
			milliSleep(new Random().nextInt(1000));//模拟通关所花费的时间
			System.out.println("勇士" + name + "通过第一关");
		}
		
		public void pass2() {
			milliSleep(new Random().nextInt(2000));//模拟通关所花费的时间
			System.out.println("勇士" + name + "通过第二关");
		}

		public void pass3() {
			milliSleep(new Random().nextInt(3000));//模拟通关所花费的时间
			System.out.println("勇士" + name + "通过第三关");
		}
		
		public void pass4() {
			milliSleep(new Random().nextInt(4000));//模拟通关所花费的时间
			System.out.println("勇士" + name + "通过第四关");
		}
	} 

}
